//
//  LoopScrollView.m
//  Product_NEWS
//
//  Created by dllo on 16/1/7.
//  Copyright © 2016年 FCH. All rights reserved.
//

#import "LoopScrollView.h"
#import "UIImageView+WebCache.h"
#import "AppTools.h"
@interface LoopScrollView ()<UIScrollViewDelegate>
@property (nonatomic, retain) UIScrollView *myScrollView;
@property (nonatomic, retain) NSMutableArray *imageArray;
@property (nonatomic, assign) NSInteger currentIndx;
@property (nonatomic, retain) UIPageControl *pageC;
@property (nonatomic, retain) NSTimer *myTimer;
@property (nonatomic, retain) NSMutableArray *titleArray;
@property (nonatomic, retain) NSMutableArray *modelArray;
@property(nonatomic,retain)Loop *model;
@end

@implementation LoopScrollView
-(void)dealloc{
    [_myScrollView release];
    [_imageArray release];
    [_pageC release];
    [_titleArray release];
    [_myTimer release];
    [_modelArray release];
    [_model release];
    [super dealloc];
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self createSubViews];
    }
    return self;
}

- (void)createSubViews{
    [self getData];
    self.imageArray = [NSMutableArray array];
    self.titleArray = [NSMutableArray array];
    self.modelArray = [NSMutableArray array];
    
    self.myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 375 * SCREEN_WIDTH,  167 *SCREEN_HEIGHT )];
    self.myScrollView.contentSize = CGSizeMake( 375 *SCREEN_WIDTH * self.imageArray.count, 0);
    self.myScrollView.pagingEnabled = YES;
    self.myScrollView.bounces = NO;
    self.myScrollView.showsVerticalScrollIndicator = YES;
    self.myScrollView.showsHorizontalScrollIndicator = NO;
    self.myScrollView.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.myScrollView];
    
    self.myScrollView.delegate = self;
    [_myScrollView release];
    
    self.myTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    
    
}

- (void)getData{
    
    NSString *url = @"http://c.m.163.com/nc/article/headline/T1348647853363/0-20.html?from=toutiao&passport=&devId=LZtQKKEPK6bjwNYb%2BKs9qCnGyynlWoaJ8yh70DKF6gviMkyJaV5bAJGGKJJB%2FlIX&size=20&version=5.5.0&spever=false&net=wifi&lat=&lon=&ts=1451355963&sign=W1z%2F36uWkUXBeXDhCizIZWTckcQxdiu%2FkCssG%2BuJ5ZV48ErR02zJ6%2FKXOnxX046I&encryption=1&canal=appstore";
    
    [AppTools getDataWithAFNUrl:url block:^(id result) {
        NSMutableArray *array = [result objectForKey:@"T1348647853363"];
        for (NSMutableDictionary *keyDic in array) {
            NSMutableArray *arrayy = [keyDic objectForKey:@"ads"];
          
            for (NSMutableDictionary *adsDic in arrayy) {
                Loop *model = [[Loop alloc] init];
                [model setValuesForKeysWithDictionary:adsDic];
                [self.modelArray addObject:model];
                [self.imageArray addObject:model.imgsrc];
                [self.titleArray addObject:model.title];
            
                [model release];
            }
        }
        
        id firstImage = [self.imageArray firstObject];
        id lastImage = [self.imageArray lastObject];
        
        [self.imageArray addObject:firstImage];
        [self.imageArray insertObject:lastImage atIndex:0];
        //        NSLog(@"array ======= %ld", (unsigned long)self.imageArray.count);
        
        id firstTitle = [self.titleArray firstObject];
        id lastTitle = [self.titleArray lastObject];
        
        [self.titleArray addObject:firstTitle];
        [self.titleArray insertObject:lastTitle atIndex:0];
        //        NSLog(@"titleArray = %@", self.titleArray);
        
        [self layoutSubviews];
        
    } errorBlock:^(NSError *error) {
        
        
    }];
}

- (void)layoutSubviews{
    for (int i = 0; i < self.imageArray.count; i++) {
        
        UIImageView *myImageView = [[UIImageView alloc] initWithFrame:CGRectMake( 375 * SCREEN_WIDTH * i, 0,375 * SCREEN_WIDTH, 167 *SCREEN_HEIGHT )];
        Loop *model = [[Loop alloc] init];
        model.imgsrc = [self.imageArray objectAtIndex:i];
        myImageView.tag = 1000 + i;
        NSURL *url = [NSURL URLWithString:model.imgsrc];
        [myImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"background"]];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [myImageView addGestureRecognizer:tap];
        myImageView.userInteractionEnabled = YES;
        
        
        UILabel *titleLabel =[[UILabel alloc] initWithFrame:CGRectMake(10 * SCREEN_WIDTH, myImageView.frame.origin.y + 132 * SCREEN_HEIGHT, 300* SCREEN_WIDTH, 50* SCREEN_HEIGHT)];
        [myImageView addSubview:titleLabel];
        
        model.title = [self.titleArray objectAtIndex:i];
       
        titleLabel.text = model.title;
       
        titleLabel.font = [UIFont systemFontOfSize:14*SCREEN_WIDTH];
        titleLabel.textColor = [UIColor whiteColor];
        titleLabel.numberOfLines = 0;
        [titleLabel release];
        
        [self.myScrollView addSubview:myImageView];
        
        [model release];
    }
    
    self.myScrollView.contentSize = CGSizeMake(375 * SCREEN_WIDTH *self.imageArray.count, 0);
    
    self.pageC = [[UIPageControl alloc] initWithFrame:CGRectMake( 215 *SCREEN_WIDTH , 150 * SCREEN_HEIGHT, 230 * SCREEN_WIDTH, 20* SCREEN_HEIGHT)];
    self.pageC.numberOfPages = self.imageArray.count - 2;
    
    self.pageC.pageIndicatorTintColor = [UIColor lightGrayColor];
    self.pageC.currentPageIndicatorTintColor = [UIColor whiteColor];
    [self addSubview:self.pageC];
    
    self.pageC.currentPage = 0;
    self.currentIndx = 0;
    
    [self.pageC addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventValueChanged];
    self.pageC.userInteractionEnabled = YES;
    [_pageC release];
    
}


- (void)tapAction:(UITapGestureRecognizer *)tap {
   

    if ([self viewWithTag:1003]) {
        Loop *model = [self.modelArray objectAtIndex:3];
        [self.myDelegate pushDetailView:model];
    }
   
}


- (void)timerAction:(NSTimer *)timer{
    
    [UIView animateWithDuration:0.5 animations:^{
        
        [self.myScrollView setContentOffset:CGPointMake(375 *(self.currentIndx + 1) * SCREEN_WIDTH, 0)];
        
    }];
    self.currentIndx++;
    
    if (self.myScrollView.contentOffset.x == (self.imageArray.count - 1) * SCREEN_WIDTH * 375) {
        [self.myScrollView setContentOffset:CGPointMake(375 * SCREEN_WIDTH, 0)];
        self.currentIndx = 0;
    }
}

- (void)pageAction:(UIPageControl *)page{
    
    [self.myScrollView setContentOffset:CGPointMake(375 * SCREEN_WIDTH * (self.pageC.currentPage), 0) animated:YES];
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    self.pageC.currentPage = scrollView.contentOffset.x / 375 * SCREEN_WIDTH - 1;
}



// 手指接触的时候定时器停止
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    [self.myTimer invalidate];
    self.myTimer = nil;
    
}

// 手指离开的时候开始滑动
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    self.myTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
}



- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (scrollView.contentOffset.x == self.imageArray.count * SCREEN_WIDTH * 375) {
        CGPoint temp = self.myScrollView.contentOffset;
        temp.x =375 * SCREEN_WIDTH * 1;
        self.myScrollView.contentOffset = temp;
    }
    if (scrollView.contentOffset.x == 0) {
        CGPoint temp = self.myScrollView.contentOffset;
        temp.x = 375 * SCREEN_WIDTH * (self.imageArray.count - 2);
        self.myScrollView.contentOffset = temp;
    }
    
}

@end
